﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;

using ZoneFiveSoftware.Common.Data;
using ZoneFiveSoftware.Common.Data.Fitness;
using ZoneFiveSoftware.Common.Data.GPS;

using BENBUN.Properties;
using BENBUN.UI.Forms;
using BENBUN.WIW;
using BENBUN.Utils.Web;

namespace BENBUN.Utils
{
    public class Controller
    {
        private static Controller instance = new Controller();

        private string _sessionToken = null;

        public string SessionToken
        {
            get
            {
                string version = GetType().Assembly.GetName().Version.ToString(3);
                if (_sessionToken == null)
                {
                    _sessionToken = Session.getToken(version);
                }

                return _sessionToken;
            }
        }

        public bool setIcon(string ReferenceId, int newIcon)
        {
            string apiURL = Settings.Settings.URLBaseAPI + "api.php";

            StringBuilder param = new StringBuilder("", 500);
            param.Append("token=" + Controller.GetInstance().SessionToken);
            param.Append("&action=setIcon");
            param.Append("&id=" + ReferenceId);
            param.Append("&icon=" + newIcon.ToString());
            string APIResponse = APIFactory.doAPI(apiURL, param.ToString());

            if (APIResponse == null)
            {
                MessageBox.Show("Communication Failure with WIW Server", "WIW Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }
            else
            {
                XmlDocument doc = new XmlDocument();

                try
                {
                    doc.LoadXml(APIResponse);
                    XmlNodeList nodes = doc.SelectNodes("/api/response");

                    if (nodes[0].InnerText != "0000")
                    {
                        MessageBox.Show("API Error : " + nodes[0].InnerText, "WIW Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return false;
                    }
                    else
                    {
                       return true;
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("API Error : Invalid Response" + Environment.NewLine + APIResponse, "WIW Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }

        }

        public bool purgeActivity(string ReferenceId)
        {
            string apiURL = Settings.Settings.URLBaseAPI + "api.php";

            StringBuilder param = new StringBuilder("", 500);
            param.Append("token=" + Controller.GetInstance().SessionToken);
            param.Append("&action=purge");
            param.Append("&id=" + ReferenceId);
            string APIResponse = APIFactory.doAPI(apiURL, param.ToString());

            if (APIResponse == null)
            {
                MessageBox.Show("Communication Failure with WIW Server", "WIW Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }
            else
            {
                XmlDocument doc = new XmlDocument();

                try
                {
                    doc.LoadXml(APIResponse);
                    XmlNodeList nodes = doc.SelectNodes("/api/response");

                    if (nodes[0].InnerText != "0000")
                    {
                        MessageBox.Show("API Error : " + nodes[0].InnerText, "WIW Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("API Error : Invalid Response" + Environment.NewLine + APIResponse, "WIW Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }

        }
        public bool Export(IActivity activity, bool supressScreen)
        {
            string apiURL = Settings.Settings.URLBaseAPI + "api.php";

            StringBuilder param = new StringBuilder("", 500);
            param.Append("token=" + Controller.GetInstance().SessionToken);
            param.Append("&action=upload");
            param.Append("&id=" + activity.ReferenceId);
            param.Append("&date=" + activity.StartTime.ToLocalTime().ToString("dd-MM-yyyy"));
            param.Append("&zone=" + activity.StartTime.ToLocalTime().ToString("zzz"));
            if (activity.HasStartTime)
            {
                param.Append("&time=" + activity.StartTime.TimeOfDay.ToString());
            }
            else
            {
                param.Append("&time=--:--:--");
            }

            ActivityInfo info = ActivityInfoCache.Instance.GetInfo(activity);
            string up = info.TotalAscendingMeters(Plugin.GetApplication().Logbook.ClimbZones[0]).ToString();
            string down = info.TotalDescendingMeters(Plugin.GetApplication().Logbook.ClimbZones[0]).ToString();

            param.Append("&duration=" + info.Time.TotalSeconds.ToString());
            param.Append("&asc=" + up.ToString());
            param.Append("&desc=" + down.ToString());

            param.Append("&lat=" + activity.GPSRoute[0].Value.LatitudeDegrees);
            param.Append("&lon=" + activity.GPSRoute[0].Value.LongitudeDegrees);

            if (activity.UseEnteredData)
            {
                param.Append("&dist=" + (int)activity.TotalDistanceMetersEntered);
            }
            else
            {
                param.Append("&dist=" + (int)activity.GPSRoute.TotalDistanceMeters);
            }

            IActivityCategory parentCategory;

            string category = activity.Category.Name;
            if (activity.Category.Parent != null)
            {
                parentCategory = activity.Category.Parent;
                category = parentCategory.Name + " : " + activity.Category.Name;
                while (parentCategory.Parent != null)
                {
                    parentCategory = parentCategory.Parent;
                    category = parentCategory.Name + " : " + category;
                }
            }

            param.Append("&category=" + category);
            string APIResponse = APIFactory.doAPI(apiURL, param.ToString());

            if (APIResponse == null)
            {
                MessageBox.Show("Communication Failure with WIW Server", "WIW Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }
            else
            {
                XmlDocument doc = new XmlDocument();

                try
                {
                    doc.LoadXml(APIResponse);
                    XmlNodeList nodes = doc.SelectNodes("/api/response");

                    if (nodes[0].InnerText != "0000")
                    {
                        MessageBox.Show("API Error : " + nodes[0].InnerText, "WIW Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return false;
                    }
                    else
                    {
                        if (supressScreen)
                        {
                            LoadConfirmation confirm = new LoadConfirmation();
                            confirm.APIResponse = doc;
                            confirm.ShowDialog();
                        }
                        return true;
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("API Error : Invalid Response" + Environment.NewLine + APIResponse, "WIW Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }
        }


        public void ClearToken()
        {
            _sessionToken = null;
        }

        private Controller() { }

        public static Controller GetInstance()
        {
            return instance;
        }
    }
}
